package com.yun.many.auth.security.jwt;

import com.yun.many.spec.enums.ResultCode;
import com.yun.many.spec.vo.HttpResult;
import com.yun.many.web.spec.jackson.utils.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证失败
 */
@Slf4j
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setStatus(200);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        try {
            response.getWriter().print(JSONUtil.toJSONString(HttpResult.failure(ResultCode.UNAUTHORIZED)));
        } catch (IOException ioException) {
            log.error("JwtAuthenticationEntryPoint.commence", ioException);
        }
    }
}